﻿using System;
using System.Net;

namespace SimpleNoteLib.Config
{
    public static class SimpleNoteApiConfig
    {
        #region Fields

        private static Uri httpsApiUri;
        private static Uri httpApiUri;

        #endregion

        #region Properties

        public static string LoginApiAddress { get; set; }

        public static string ApiAddress
        {
            get
            {
                return UseHttps ? httpsApiUri.ToString() : httpApiUri.ToString();
            }
            set
            {
                if (value.EndsWith("/") == false)
                {
                    value = value + "/";
                }
                Uri uri = new Uri(value);
                httpsApiUri = new Uri("https://" + uri.Host + uri.AbsolutePath);
                httpApiUri = new Uri("http://" + uri.Host + uri.AbsolutePath);
            }
        }
        public static bool UseHttps { get; set; }
        public static string ProxyAddress { get; set; }
        public static string ProxyUser { get; set; }
        public static string ProxyPassword { get; set; }
        public static ProxyMode UseProxy { get; set; }

        internal static IWebProxy Proxy
        {
            get
            {
                switch (UseProxy)
                {
                    case ProxyMode.NoProxy:
                        return null;
                        break;
                    case ProxyMode.UseSystemDefault:
                        IWebProxy defaultProxy = WebRequest.DefaultWebProxy;
                        defaultProxy.Credentials = CredentialCache.DefaultCredentials;
                        return defaultProxy;
                        break;
                    case ProxyMode.OwnProxyConfig:
                        IWebProxy proxy = new WebProxy(ProxyAddress);
                        if (ProxyUser.Contains(@"\"))
                        {
                            string[] parts = ProxyUser.Split(new char[] { '\\' });
                            proxy.Credentials = new NetworkCredential(parts[1], ProxyPassword, parts[0]);
                        }
                        else
                        {
                            proxy.Credentials = new NetworkCredential(ProxyUser, ProxyPassword);
                        }
                        return proxy;
                        break;
                    default:
                        return WebRequest.DefaultWebProxy;
                }
            }
        }

        public static bool MergedNotesOnSaving { get; set; }

        #endregion

        static SimpleNoteApiConfig()
        {
            LoginApiAddress = "https://simple-note.appspot.com/api/login";
            ApiAddress = "https://simple-note.appspot.com/api2/";
            UseHttps = true;
            MergedNotesOnSaving = true;
        }
    }
}
